package com.example.demo.controller;

import com.example.demo.pojo.Business;
import com.example.demo.pojo.Result;
import com.example.demo.service.BusinessService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class BusinessController {
    @Autowired
    BusinessService businessService;

    @GetMapping("/bus")
    public List<Business> selectAllBusiness(){
        List<Business> businessList = businessService.selectAllBusiness();
        for (Business business : businessList) {
            businessService.call_checkbusiness(business.getBusiness_id());
        }
        return businessList;
    }

    @PostMapping("/bus/search")
    public Business selectBusiness(@RequestBody Business business){
        int business_id = business.getBusiness_id();
        Business business1 = businessService.selectBusinessById(business_id);
        if (business1 != null){
            return businessService.selectBusinessById(business_id);
        }else{
            return null;
        }
    }

    @PostMapping("/bus/add")
    public Result addBusiness(@RequestBody Business business){
        if (business!= null){
            businessService.addBusiness(business);
            return Result.success();
        }else{
            return Result.error("添加失败");
        }
    }

    @PutMapping("/bus/update/{id}")
    public Result updateBusiness(@PathVariable int id, @RequestBody Business business){
        if (business!= null){
            business.setBusiness_id(id);
            businessService.updateBusiness(business);
            businessService.call_checkbusiness(id);
            return Result.success();
        }else{
            return Result.error("更新失败");
        }
    }

    @DeleteMapping("/bus/delete/{id}")
    public Result deleteBusiness(@PathVariable int id){
        if (id > 0){
            businessService.deleteBusiness(id);
            return Result.success();
        }else{
            return Result.error("删除失败");
        }
    }

    @PostMapping("/bus/import")
    public Result importBusiness(@RequestBody List<Business> businesslist){
        if (businesslist != null){
            businessService.changeAllBusiness(businesslist);
            return Result.success();
        }else{
            return Result.error("导入失败");
        }
    }

    @GetMapping("/bus/bus_num")
    public Result bus_num() {
        int num = businessService.bus_num();
        if (num != 0){
            businessService.bus_num();
            return Result.success(num);
        }
        return Result.error("获取总员工数失败");
    }

}
